package config

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"
)

const dbName = "config"

type ConfigDbModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
}

func (this *ConfigDbModel) FindOne(filter Config, opts *options.FindOneOptions) *mongo.SingleResult {
	filterByte, err := this.CommonFunc.BsonMarshal(filter)
	if err != nil {
		panic(err)
	}
	return this.MDB.Collection(dbName).FindOne(context.TODO(), filterByte, opts)
}

func (this *ConfigDbModel) Upsert(update Config) {
	filter := update
	filter.Value = ""
	filterBsonD, err := this.CommonFunc.StructToBsonD(filter)
	if err != nil {
		panic(err)
	}
	opts := options.Update().SetUpsert(true)
	updateBsonD,err := this.CommonFunc.StructToBsonD(update)
	if err != nil {
		panic(err)
	}
	updateSet := bson.D{{"$set", updateBsonD}}
	_, err = this.MDB.Collection(dbName).UpdateOne(context.Background(), filterBsonD, updateSet, opts)
	if err != nil {
		panic(err)
	}
}
